﻿/// <reference path="jquery-1.4.1.js"/>

$.fn.ellipsisText = function () {
    return this.each(function () {
        var elem = $(this);
        var parent = elem.parent();
        var maxHeight = parent.height() - (elem.offset().top - parent.offset().top);
        if (maxHeight <= 0) {
            return;
        }
        elem.css("visibility", "hidden");
        var content = elem.data("ellipsisText_origContent");
        if (!content) {
            content = elem.text();
            elem.data("ellipsisText_origContent", content);
        } else {
            elem.text(content);
        }
        if (elem.height() <= maxHeight) {
            elem.css("visibility", "visible");
            return;
        };
        var lastHeight = elem.height();
        var contentFitInLastHeight = content;
        while (content != "" && elem.height() > maxHeight) {
            if (elem.height() < lastHeight) {
                lastHeight = elem.height();
                contentFitInLastHeight = content;
            }
            content = content.substring(0, content.length - 1);
            elem.html(elem.text(content).html() + "&hellip;");
        }
        if (content === "") {
            // at least display 1 line
            elem.text(elem.text(contentFitInLastHeight).html() + "&hellip;");
        }
        elem.css("visibility", "visible");
    });
};
